package com.lyf.service.impl;

import com.lyf.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;

@Service
@Transactional
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public int saveUserCount(Integer userId) {
        //根据不同用户的id生成调用次数的key
        String limitKey = "Limit_" + userId;

        //获取redis指定key的调用次数
        String limitNum = stringRedisTemplate.opsForValue().get(limitKey);
        int limit = -1;
        if(limitNum == null) {
            //第一次调用放入redis，并初始化为0
            stringRedisTemplate.opsForValue().set(limitKey,"0",3600, TimeUnit.SECONDS);
        } else {
            //不是第一次调用就+1
            limit = Integer.parseInt(limitNum) + 1;
            stringRedisTemplate.opsForValue().set(limitKey,String.valueOf(limit), 3600, TimeUnit.SECONDS);
        }

        return limit;//返回调用次数;-1就是没有调用过
    }

    @Override
    public boolean getUserCount(Integer userId) {
        //拼接调用次数key
        String limitKey = "Limit_" + userId;
        //根据key获取redis中调用次数
        String limitNum = stringRedisTemplate.opsForValue().get(limitKey);
        if(limitNum == null){
            //为空说明不正常
            log.error("该用户没有访问申请验证记录，疑似异常");
            return true;
        }
        //访问10次就超过
        return Integer.parseInt(limitNum) > 10;
        //false：没超过     true：超过
    }
}
